package client

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/encrypt"
	"net/http"
	"net/url"
	"sort"
	"strings"
	"time"
)

// 联速

const postPayGatewayUrl = "http://superadm.hy.huiyingzf.com/Pay_Index.html"

var appid = "210391291"                         //商户号
var apiKey = "wzdu7a5teg60ex98p2s8lecjbtzw5z9j" //商户APIKEY

var lsuHost = "http://superadm.hy.huiyingzf.com"
var payOrderUrl = "/Pay_Index.html"             // 网关地址，用户统一下单接口
var orderSearchUrl = "/Pay_Trade_query.html"    // 订单查询接口
var orderStatusUrl = "/Shop_Trade_query.html"   // 订单状态查询接口
var dfPayUrl = "/Payment_Dfpay_add.html"        // 代付提交接口
var dfPaySearchUrl = "Payment_Dfpay_query.html" // 代付查询接口
var payBalance = "/Payment_Dfpay_balance.html"  // 账户余额接口
var payNotifyUrl = "/api/charge/orderResultNotify"
var pay_callbackurl = "/api/charge/callBackHtml"

//var payNotifyUrl = "https://api.zhou618.com/api/charge/orderResultNotify"

type PayResult struct {
	Code string `json:"code"`
	Msg  string `json:"msg"`
}

// 联速的签名方法
func LsuSign(params map[string]string) (string, error) {
	var dataParams string
	//ksort
	var keys []string
	for k := range params {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	//拼接
	for _, k := range keys {
		//fmt.Println("key:", k, "Value:", params[k])
		dataParams = dataParams + k + "=" + params[k] + "&"
	}

	dataParams = dataParams + "key=" + apiKey
	fmt.Println("最后的str：", dataParams)
	ff := strings.ToUpper(encrypt.Md5(dataParams))
	fmt.Println("sign：", ff)

	return ff, nil
}

// 下单接口
func LsPay(callbackhost, pay_orderid, pay_bankcode, pay_amount, pay_productname, pay_productnum, pay_productdesc, pay_producturl string) (string, error) {

	if len(pay_orderid) < 1 || len(pay_bankcode) < 1 || len(pay_amount) < 1 || len(pay_productname) < 1 {
		return "LsPay", errors.New("第三方支付缺少参数")
	}
	data := make(map[string]string) //构造map数据
	data["pay_memberid"] = appid
	data["pay_orderid"] = pay_orderid
	data["pay_applydate"] = time.Now().Format("2006-01-02 15:04:05")
	data["pay_bankcode"] = pay_bankcode
	data["pay_notifyurl"] = callbackhost + payNotifyUrl
	data["pay_callbackurl"] = callbackhost + pay_callbackurl
	data["pay_amount"] = pay_amount
	sign, err := LsuSign(data)
	if err != nil {
		return "", err
	}
	data["pay_md5sign"] = sign

	if len(pay_productnum) > 0 {
		data["pay_productnum"] = pay_productnum
	}
	if len(pay_productdesc) > 0 {
		data["pay_productdesc"] = pay_productdesc
	}
	if len(pay_producturl) > 0 {
		data["pay_producturl"] = pay_producturl
	}
	data["pay_productname"] = pay_productname

	//reply := fmt.Sprintf("<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>"+
	//	"<meta charset=\"UTF-8\">"+
	//	"<meta content=\"width=device-width, minimum-scale=1.0, maximum-scale=1.0\" name=\"viewport\">"+
	//	"<title>智能收银台</title>"+
	//	"<script type=\"text/javascript\" src=\"/syt/js/jquery.js\"></script>"+
	//	"</head>"+
	//	"<body>"+
	//	"<form id='request' action='%s' method='post'>"+
	//	"<input type=\"hidden\" value='%s' name='pay_amount' />"+
	//	"<input type=\"hidden\" value='%s' name='pay_applydate' />"+
	//	"<input type=\"hidden\" value='%s' name='pay_bankcode' />"+
	//	"<input type=\"hidden\" value='%s' name='pay_callbackurl' />"+
	//	"<input type=\"hidden\" value='%s' name='pay_memberid' />"+
	//	"<input type=\"hidden\" value='%s' name='pay_notifyurl' />"+
	//	"<input type=\"hidden\" value='%s' name='pay_orderid' />"+
	//	"<input type=\"hidden\" value='%s' name='pay_md5sign' />"+
	//	"<input type=\"hidden\" type='submit' value='登录' /></form>"+
	//	"<script>document.getElementById(\"request\").submit();\n    </script>"+
	//	"</body></html>", postPayGatewayUrl, pay_amount, data["pay_applydate"], pay_bankcode, data["pay_notifyurl"], appid, callbackhost+payNotifyUrl, pay_orderid, sign)

	//跳转链接
	reply, err := HttpDo(data, lsuHost+payOrderUrl)
	if err != nil {
		return "", err
	}
	//返回值判断
	failResp := &pageFailResp{}
	err = json.Unmarshal([]byte(reply), &failResp)
	if err == nil {
		//如果返回的数据是json形式的错误信息, 则返回错误
		return "", errors.New(failResp.Msg)
	}
	reply = strings.ReplaceAll(reply, "<script>location.href='", "")
	reply = strings.ReplaceAll(reply, "';</script>", "")
	return reply, nil
}

// 当GatewayHtmlUrl调用失败时候会返回json格式的错误信息
// 正确信息是一段JS跳转代码, 需要采用replace的方式进行获取到真实的付款链接
type pageFailResp struct {
	Status string `json:"status"` //状态码	非1为失败状态
	Msg    string `json:"msg"`    //订单号	错误信息
}

// 交易查询
func LsQuery(pay_orderid string) (string, error) {
	data := make(map[string]string) //构造map数据

	data["pay_memberid"] = appid
	data["pay_orderid"] = pay_orderid
	sign, err := LsuSign(data)
	if err != nil {
		return "", err
	}
	data["pay_md5sign"] = sign
	reply, err := HttpDo(data, lsuHost+orderSearchUrl)
	return reply, err
}

// 代付支付
func LsDfPay(pay_orderid string) (string, error) {
	data := make(map[string]string) //构造map数据

	reply, err := HttpDo(data, lsuHost+dfPayUrl)
	return reply, err
}

// http Post发送
func HttpDo(data map[string]string, path string) (string, error) {
	client := &http.Client{}
	//post要提交的数据
	DataUrlVal := url.Values{}
	for key, val := range data {
		DataUrlVal.Add(key, val)
	}
	fmt.Println(path)
	req, err := http.NewRequest("POST", path, strings.NewReader(DataUrlVal.Encode()))
	if err != nil {
		return "", err
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")

	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	global.Log.Debugf("LiansuHttpDo-body:%v", string(body))

	return string(body), nil
}
